﻿/*
 * Special thanks to Rob Conery for this code from Kona.
 * http://mvcsamples.codeplex.com/
 * */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace MVCCentral.Framework.Mvc
{
    public static class UrlHelperExtensions
    {


        public static string GetSiteUrl(this UrlHelper helper)
        {
            var ctx = HttpContext.Current;
            string port = ctx.Request.ServerVariables["SERVER_PORT"];
            if (port == null || port == "80" || port == "443")
            {
                port = "";
            }
            else
            {
                port = ":" + port;
            }

            string protocol = ctx.Request.ServerVariables["SERVER_PORT_SECURE"]; ;
            if (protocol == null || protocol == "0")
            {
                protocol = "http://";
            }
            else
            {
                protocol = "https://";
            }

            string appPath = ctx.Request.ApplicationPath;
            if (appPath == "/")
                appPath = "";

            string result = protocol + ctx.Request.ServerVariables["SERVER_NAME"] + port + appPath;
            return result;
        }

        public static string GetSiteUrl(this HttpContext context)
        {
            HttpContextBase wrapper = new HttpContextWrapper(context);
            return GetSiteUrl(wrapper as HttpContextBase, true);
        }

        public static string GetSiteUrl(HttpContextBase ctx, bool usePort)
        {
            string port = ctx.Request.ServerVariables["SERVER_PORT"];
            if (port == null || port == "80" || port == "443")
            {
                port = "";
            }
            else
            {
                port = ":" + port;
            }

            string protocol = ctx.Request.ServerVariables["SERVER_PORT_SECURE"]; ;
            if (protocol == null || protocol == "0")
            {
                protocol = "http://";
            }
            else
            {
                protocol = "https://";
            }

            string appPath = ctx.Request.ApplicationPath;
            if (appPath == "/")
                appPath = "";

            string result = protocol + ctx.Request.ServerVariables["SERVER_NAME"] + port + appPath;
            return result;

        }
    }
}
